package parser

import (
	"crawler/engine"
	"crawler/model"
	"fmt"
	"regexp"
	"strconv"
)

var (
	ageRe     = regexp.MustCompile(`<div data-v-8b1eac0c="" class="m-btn purple">([0-9]+)岁</div>`)
	weightRe  = regexp.MustCompile(`<div data-v-8b1eac0c class="m-btn purple">([\d]+)kg</div>`)
	xingzuoRe = regexp.MustCompile(`<div data-v-8b1eac0c class="m-btn purple">([\\u4e00-\\u9fa5]+)\(\d{1,2}.\d{1,2}-\d{1,2}.\d{1,2}\)</div>`)
	hokouRe   = regexp.MustCompile("<div[^>]+>籍贯:([\u4e00-\u9fa5]+)</div>")
)

// 猜你喜欢
// var guessRe = regexp.MustCompile(`<a class="exp-user-name"[^>]*href="([^<>"]+album.zhenai.com/u/[\d]+)"[^>]*>([^<]+)</a>`)
var idUrlRe = regexp.MustCompile(`[^><]*album.zhenai.com/u/([\d]+)`)

func ParseProfile(contents []byte, url string, name string, profile model.Profile) engine.ParserResult {
	profile.Name = name
	if weight, err := strconv.Atoi(extractString(contents, weightRe)); err == nil {
		profile.Weight = weight
	}

	if profile.Age == 0 {
		profile.Age = extractInt(contents, ageRe)
	}

	profile.Hokou = extractString(contents, hokouRe)
	profile.Xingzuo = extractString(contents, xingzuoRe)
	//profile.House = extractString(contents, houseRe)
	//profile.Car = extractString(contents, carRe)

	fmt.Printf("profile item %v\n", profile)

	result := engine.ParserResult{
		Items: []engine.Item{
			{
				Url:     url,
				Type:    "zhenai",
				Id:      extractString([]byte(url), idUrlRe),
				Payload: profile,
			},
		},
	}

	// // 猜你喜欢提取到的用户信息添加到请求队列中
	// matches := guessRe.FindAllSubmatch(contents, -1)
	// for _, m := range matches {
	// 	result.Requests = append(result.Requests, engine.Request{
	// 		Url:        string(m[1]),
	// 		ParserFunc: ProfileParser(string(m[2]), model.Profile{}),
	// 	})
	// }

	return result
}

func extractString(c []byte, re *regexp.Regexp) string {
	match := re.FindSubmatch(c)
	if len(match) > 1 {
		return string(match[1])
	}
	return ""
}

func ProfileParser(name string, cityProfile model.Profile) engine.ParserFunc {
	return func(c []byte, url string) engine.ParserResult {
		return ParseProfile(c, url, name, cityProfile)
	}
}

func extractInt(c []byte, re *regexp.Regexp) int {
	match := re.FindSubmatch(c)
	fmt.Printf("extractInt matches: %v\n", match)
	if len(match) >= 2 {
		retInt, err := strconv.Atoi(string(match[1]))
		if err != nil {
			return retInt
		}
	}
	return -1
}
